package com.atguigu.gmall.common.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 李旭
 * @Time: 9:18
 * @Description:
 *
 * RequestInterceptor  : 请求拦截器 （远程调用）
 */
//@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1号  请求头中的用户ID  传递给 2号
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();

        //判断
        if(null != requestAttributes){
            //1号对象
            HttpServletRequest request = requestAttributes.getRequest();
            if(null != request){
                //真实用户
                String userId = request.getHeader("userId");
                if(!StringUtils.isEmpty(userId)){
                    //RequestTemplate : 即将马上发出远程调用请求对象  2号
                    requestTemplate.header("userId",userId);
                }
                //临时用户
                String userTempId = request.getHeader("userTempId");
                if(!StringUtils.isEmpty(userTempId)){
                    //RequestTemplate : 即将马上发出远程调用请求对象  2号
                    requestTemplate.header("userTempId",userTempId);
                }

            }
        }
    }
}
